#include "multicastrecv.h"
#include "ui_multicastrecv.h"
#include <QDebug>

MultiCastRecv::MultiCastRecv(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MultiCastRecv)
{
    ui->setupUi(this);

    connect(&msocket,&QUdpSocket::readyRead,this,&MultiCastRecv::recv_multicast);

}

MultiCastRecv::~MultiCastRecv()
{
    delete ui;
}

void MultiCastRecv::on_bindBt_clicked()
{
    //获取端口号
    QString port = ui->portEdit->text();
    msocket.bind(QHostAddress::AnyIPv4,port.toUShort());

}

void MultiCastRecv::recv_multicast()
{
    QHostAddress appaddr;
    quint16 port;
    QByteArray array;  //要另外分配空间

    qint64 size = msocket.bytesAvailable();  //获取当前有多少字节数据可读

    array.resize(size);   //分配空间
    msocket.readDatagram(array.data(),array.size(),&appaddr,&port);

    ui->textBrowser->append(QString(array));

}

void MultiCastRecv::on_addBt_clicked()
{
    //获取组播地址
    QString multiAddress = ui->ipEdit->text();
    //加入组播组
    if(msocket.joinMulticastGroup(QHostAddress(multiAddress)))
    {
        //把地址添加到列表中去
        ui->listWidget->addItem(multiAddress);

    }
    else
    {
        qDebug()<<"加入组播失败！";
    }
}

void MultiCastRecv::on_listWidget_itemDoubleClicked(QListWidgetItem *item)
{
    //
    QString multiAddress = item->text();

    if(msocket.leaveMulticastGroup(QHostAddress(multiAddress)))
    {
        delete item;
    }
    else{
        qDebug()<<"退出失败";
    }
}



